package com.yanx.framework.advice;

import cn.hutool.core.codec.Base64;
import com.yanx.common.annotation.ApiResult;
import com.yanx.common.utils.Json_;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Order(0)
@ControllerAdvice
public class EncodeResponseBodyAdvice extends BaseResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        ApiResult resultAnnotation = AnnotationUtils.findAnnotation(returnType.getAnnotatedElement(), ApiResult.class);
        return isApiResult(returnType) && resultAnnotation.encode();
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return Base64.encode(Json_.toJson(body));
    }

}
